<template>
  <ych-modal
    :fullscreen="true"
    :title="title"
    :visible="visible"
    :confirmLoading="spinning > 0"
    @ok="handleOk"
    @cancel="handleCancel"
    :cancelText="$t('m.common.button.close')">

    <a-spin :spinning="spinning > 0">
      <a-form :form="form">
        <a-row class="grid-row">
          <a-col v-bind="colLayout2.cols" class="grid-col">
            <a-form-item :label="$t('m.system.sysfillrule.entity.ruleName')" :label-col="colLayout2.labelCol" :wrapper-col="colLayout2.wrapperCol">
              <a-input placeholder="" v-decorator="['ruleName', validatorRules.ruleName]"/>
            </a-form-item>
          </a-col>
          <a-col v-bind="colLayout2.cols" class="grid-col">
            <a-form-item :label="$t('m.system.sysfillrule.entity.ruleCode')" :label-col="colLayout2.labelCol" :wrapper-col="colLayout2.wrapperCol">
              <a-input placeholder="" v-decorator="['ruleCode', validatorRules.ruleCode]"/>
            </a-form-item>
          </a-col>
          <a-col v-bind="colLayout2.fixed.cols" class="grid-col">
            <a-form-item :label="$t('m.system.sysfillrule.entity.ruleDescription')" :label-col="colLayout2.fixed.labelCol" :wrapper-col="colLayout2.fixed.wrapperCol">
              <a-textarea placeholder="" v-decorator="['ruleDescription', {}]"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- 规则设计 -->
      <a-tabs v-model="tabs.activeKey">
        <a-tab-pane :tab="$t('m.system.sysfillrule.other.localRules_tab')" :key="tabs.part.key" forceRender>
          <a-alert type="info" showIcon :message="$t('m.system.sysfillrule.other.localRules_tip')"/>

          <vxe-toolbar>
            <template #buttons>
              <a-button type="primary" icon="plus"  @click="insertRow('partRuleTable', tabs.part.dataSource, tabs.part.initData, 'digits')">{{ $t('m.common.button.add') }}</a-button>
              <span class="action-button-gap"></span>
              <a-button type="default" icon="minus" @click="deleteRow('partRuleTable', tabs.part.dataSource)">{{ $t('m.common.button.delete') }}</a-button>
            </template>
          </vxe-toolbar>

          <vxe-table
            ref="partRuleTable"
            border
            :scroll-y="{enabled: false}"
            class="sortable-row-vxe"
            show-header-overflow
            show-overflow
            :row-config="{isHover: true, useKey: true, keyField: 'id'}"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            :edit-rules="tabs.part.validRules"
            :data="tabs.part.dataSource">
            <vxe-column width="60" align="center">
              <template #default>
                <span class="drag-btn">
                  <i class="vxe-icon-num-list"></i>
                </span>
              </template>
            </vxe-column>
            <vxe-column type="checkbox" width="60"></vxe-column>
            <vxe-column type="seq" :title="$t('m.common.label.number')" width="60"></vxe-column>
            <vxe-column field="digits" :title="$t('m.system.sysfillrule.entity.digits')" :edit-render="{name: 'input',attrs: {type: 'number'}}"></vxe-column>
            <vxe-column field="pattern" :title="$t('m.system.sysfillrule.entity.pattern')" :edit-render="{name: 'input'}"></vxe-column>
            <vxe-column field="message" :title="$t('m.system.sysfillrule.entity.message')" :edit-render="{name: 'input'}"></vxe-column>
          </vxe-table>
        </a-tab-pane>
        <a-tab-pane :tab="$t('m.system.sysfillrule.other.localRules_tab')" :key="tabs.global.key" forceRender>
          <a-alert type="info" showIcon :message="$t('m.system.sysfillrule.other.globalRules_tip')"/>

          <vxe-toolbar>
            <template #buttons>
              <a-button type="primary" icon="plus" @click="insertRow('globalRuleTable', tabs.global.dataSource, tabs.global.initData, 'priority')">{{ $t('m.common.button.add') }}</a-button>
              <span class="action-button-gap"></span>
              <a-button type="default" icon="minus" @click="deleteRow('globalRuleTable', tabs.global.dataSource)">{{ $t('m.common.button.delete') }}</a-button>
            </template>
          </vxe-toolbar>

          <vxe-table
            ref="globalRuleTable"
            border
            :scroll-y="{enabled: false}"
            class="sortable-row-vxe"
            show-header-overflow
            show-overflow
            :row-config="{isHover: true, useKey: true, keyField: 'id'}"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            :edit-rules="tabs.global.validRules"
            :data="tabs.global.dataSource">
            <vxe-column width="60" align="center">
              <template #default>
                <span class="drag-btn">
                  <i class="vxe-icon-num-list"></i>
                </span>
              </template>
            </vxe-column>
            <vxe-column type="checkbox" width="60"></vxe-column>
            <vxe-column type="seq" :title="$t('m.common.label.number')" width="60"></vxe-column>
            <vxe-column field="priority" :title="$t('m.system.sysfillrule.entity.priority')" :formatter="formatterPriority"
                        :edit-render="{name: 'select', options: priorityOptions,defaultValue:'1'}"></vxe-column>
            <vxe-column field="pattern" :title="$t('m.system.sysfillrule.entity.pattern')" :edit-render="{name: 'input'}"></vxe-column>
            <vxe-column field="message" :title="$t('m.system.sysfillrule.entity.message')" :edit-render="{name: 'input'}"></vxe-column>
          </vxe-table>
        </a-tab-pane>
      </a-tabs>
    </a-spin>
  </ych-modal>
</template>

<script>
  import { httpAction } from '@/api/manage'
  import YchConstant from "@/api/YchConstant";
  import {YchVxeTableMixin} from '@/mixins/YchVxeTableMixin'
  import { validateDuplicateValue} from '@/utils/util'
  import {GardLayoutMixin} from '@/mixins/GardLayoutMixin'

  export default {
    name: 'SysCheckRuleModal',
    mixins: [YchVxeTableMixin,GardLayoutMixin],
    data() {
      const patternValid = ({cellValue, row}) => {
        let valid = true
        if(cellValue){
          try {
            new RegExp(cellValue)
          } catch (e) {
            valid = false
          }
        }
        if(!valid){
          return new Error(this.$t('m.system.sysfillrule.other.pattern_tip'))
        }

      }
      return {
        priorityOptions:[
          {
            label: this.$t('m.system.sysfillrule.other.priorityOptions1'),
            value: '1'
          },
          {
            label: this.$t('m.system.sysfillrule.other.priorityOptions0'),
            value: '0'
          }
        ],
        validatorRules: {
          ruleName: { rules: [{ required: true, message:this.$t('m.common.tip.verify_required') },] },
          ruleCode: {
            rules: [
              { required: true, message: this.$t('m.common.tip.verify_required') },
              { validator: (rule, value, callback) => validateDuplicateValue('sys_check_rule', 'rule_code', value, this.model.id, callback) }
            ]
          },
        },
        tabs: {
          activeKey: 'part',
          global: {
            key: 'global',
            dataSource: [],
            initData:{
              priority:'1',
              pattern:'',
              message:''
            },
            validRules: {
              priority:[
                { required: true, message: this.$t('m.common.tip.verify_required') }
              ],
              pattern: [
                { required: true, message: this.$t('m.common.tip.verify_required') },
                {validator: patternValid},
              ],
              message: [
                { required: true, message: this.$t('m.common.tip.verify_required') },
              ],
            },
          },
          part: {
            key: 'part',
            dataSource: [],
            initData:{

            },
            validRules: {
              digits:[
                { required: true, message: this.$t('m.common.tip.verify_required') },
                { pattern: /^[1-9]\d*$/, message:this.$t('m.common.tip.positive_digits_tip')}
              ],
              pattern: [
                { required: true, message: this.$t('m.common.tip.verify_required') },
                {validator: patternValid},
              ],
              message: [
                { required: true, message: this.$t('m.common.tip.verify_required') },
              ],
            },
          }
        },
        url: {
          add: YchConstant.PREFIX_SYSTEM + '/checkRule/add',
          edit: YchConstant.PREFIX_SYSTEM + '/checkRule/edit',
        },
      }
    },
    created() {
    },
    methods: {
      formatterPriority({cellValue}){
        let item = this.priorityOptions.find(item => item.value === cellValue)
        return item ? item.label : ''
      },
      add() {
        this.edit({})
      },
      edit(record) {
        this.form.resetFields()
        this.tabs.activeKey = this.tabs.part.key
        this.tabs.global.dataSource = []
        this.tabs.part.dataSource = [{ digits: '', pattern: '', message: '' }]
        this.model = Object.assign({}, record)
        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(this.lodash.pick(this.model, 'ruleName', 'ruleCode', 'ruleDescription'))
          // 子表数据
          let ruleJson = this.model.ruleJson
          if (ruleJson) {
            let ruleList = JSON.parse(ruleJson)
            // 筛选出全局规则和局部规则
            let global = [], part = [], priority = '1'
            ruleList.forEach(rule => {
              if (rule.digits === '*') {
                global.push(Object.assign(rule, { priority }))
              } else {
                priority = '0'
                part.push(rule)
              }
            })
            this.tabs.global.dataSource = global
            this.tabs.part.dataSource = part
          }
          // 启用排序功能
          this.rowDrop('partRuleTable', (newIndex, oldIndex) => {
            this.afterRowDrop(newIndex, oldIndex, this.tabs.part.dataSource);
          })
          this.rowDrop('globalRuleTable', (newIndex, oldIndex) => {
            this.afterRowDrop(newIndex, oldIndex, this.tabs.global.dataSource);
          })
        })
      },
      close() {
        this.$emit('close')
        this.visible = false
      },
      async beforeSave(formData) {
        const partValues = await this.getTableDataSource(this.$refs.partRuleTable, this.tabs.part.dataSource);
        if (partValues === false) {
          // 返回空，终止保存动作
          this.tabs.activeKey='part'
          return
        }
        const globalValues = await this.getTableDataSource(this.$refs.globalRuleTable, this.tabs.global.dataSource);
        if (globalValues === false) {
          // 返回空，终止保存动作
          this.tabs.activeKey='global'
          return
        }
        // 整合两个子表的数据
        let firstGlobal = [], afterGlobal = []
        globalValues.forEach(v => {
          v.digits = '*'
          if (v.priority === '1') {
            firstGlobal.push(v)
          } else {
            afterGlobal.push(v)
          }
        })
        let concatValues = firstGlobal.concat(partValues).concat(afterGlobal)
        let subValues = concatValues.map(i => this.lodash.pick(i, 'digits', 'pattern', 'message'))
        let ruleJson = JSON.stringify(subValues)
        formData = Object.assign(this.model, formData, { ruleJson })
        return formData;
      },
    }
  }
</script>

<style lang="scss" scoped></style>
